<?php
/**
 * Created by PhpStorm.
 * User: Jmashimaro
 * Date: 2015/2/4
 * Time: 17:45
 */
class StoreApp extends StorebaseApp {

    private $common;
    private $size=10;
    public function __construct() {
        $this->common = new CommonApp();
    }
    /**
     * 店铺信息详情
     * @author jyx
     * @date 2015/08/11
     */
    public function index() {
        $action = '店铺信息详情';
        setLogParameter($action);       //设置日志的参数
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }
        $content=$brand = $store = $cate = '';
        $min = $this->get_gp ( 'min', 'G' );            //最小价格
        $max = $this->get_gp ( 'max', 'G' );            //最大价格
        $store_id = $this->get_gp('store_id', 'G');
        $offset = $this->get_gp('offset', 'G');
        $size = $this->get_gp('size', 'G');
        $sort = $this->get_gp ( 'sort', 'G' );          ///排序,1:上架时间,2:价钱从高到低,3:价钱从底到高,4:销量最高排序,5:喜欢的最多
        $sort = $sort ? intval($sort):1;
        $store_id = $store_id ? intval($store_id) : 0;
        $offset = $offset ? intval($offset) : 0;
        $size = $size ? intval($size) : 10;
        if (!$store_id) {
            $this->ajax_return(FLAG_ERROR, '错误的store_id!');
        }
        /* 店铺信息 */
        $model = m('store');
        $sql = "SELECT store_id,store_name,store_logo,iphone_banner,brand_describe,video_link FROM ".DB_PREFIX."store WHERE store_id={$store_id}";
        $data['store'] = $model->getRow($sql);
        if (!$data['store']) {
            $this->ajax_return(FLAG_ERROR, '店铺信息不存在!');
        }
        $data['store']['store_logo'] = $data['store']['store_logo'] ? QINIU_URL.$data['store']['store_logo'].STORE_LOGO : '';
        $data['store']['iphone_banner'] = $data['store']['iphone_banner'] ? QINIU_URL.$data['store']['iphone_banner'].STORE_BANNER : '';

        //获取我与商铺是否关注
        //$user_id = $this->checkLogin();
        $user_id =85;
        $sql = 'SELECT user_id FROM '.DB_PREFIX."collect WHERE user_id={$user_id} AND type='store' AND item_id={$store_id}";

        $info = $model->getRow($sql);
        if ($info) {
            $data['store']['relation'] = 1;
        } else {
            $data['store']['relation'] = 0;
        }

        $data["store"]["description"] = $data["store"]["brand_describe"];

        // 分类
        // 多分类用半角逗号间隔
        if( $cate_id = $this->get_gp ( 'cate_id', 'G' ) )
        {
            //判断是不是多个分类
            if ( stristr($cate_id,',') !== false )
            {
                foreach ( explode ( ',', $cate_id ) as $temp )
                {
                    $cate .= vsprintf ( ' ( cate_id_one:%u OR cate_id_two:%u OR cate_id_three:%u ) OR', array_fill (0,3,$temp) );
                }

            }else{
                $cate .= vsprintf ( ' ( cate_id_one:%u OR cate_id_two:%u OR cate_id_three:%u ) OR',array_fill (0,3,$cate_id));
            }
            $cate = '( ' . substr ( $cate, 0, - 3 ) . ' )';
        }
        //店铺
        //多店铺用半角逗号间隔
        if ($store_id)
        {
            if ( stristr($store_id,',') !== false )
            {
                foreach ( explode ( ',', $store_id ) as $temp )
                {
                    $store .= vsprintf ( ' store_id:%u OR', $temp );
                }
            }else{
                $store .= vsprintf ( ' store_id:%u OR', $store_id );
            }
            $store = '( ' . substr ( $store, 0, - 3 ) . ' )';
        }

        // 品牌
        // 多品牌用半角逗号间隔
        if ( $brand_id = $this->get_gp ( 'brand_id', 'G' ) )
        {
            if ( stristr($brand_id,',') !== false )
            {
                foreach ( explode ( ',', $brand_id ) as $temp )
                {
                    $brand .= sprintf ( ' brand_id:%u OR', $temp );
                }
            }else{
                $brand .= sprintf ( ' brand_id:%u OR', $brand_id );
            }
            $brand = '( ' . substr ( $brand, 0, - 3 ) . ' )';
        }
        //获取商品列表
        $res = $this->searching ($content,$cate, $brand, $min,$max, $sort, $store,$offset);
        $model  = m ( 'goods' );
        $brands = array();
        if($res['goods'])
        {
            foreach( $res['brandIds'] as $key=>$val){
                $brand_ids[]=$key;
            }
            $sql= "SELECT brand_id,brand_name,en_name FROM " .DB_PREFIX ."brand WHERE brand_id in ( ".implode (',', $brand_ids)." ) ORDER BY field(brand_id,".implode (',', $brand_ids).")";
            $datas= $model->getAll($sql);
            foreach($datas as $key=>$value){
                $brand    = $value[ 'brand_name' ] ? $value[ 'brand_name' ] : $value[ 'en_name' ];
                $brands[] = array ( 'brand_id' => $value['brand_id'], 'brand_name' => $brand, 'selectID'=>0 );
            }
            /*foreach ( $res[ 'brandIds' ] as $key => $val )
            {
                $sql      = "SELECT brand_name,en_name FROM " .DB_PREFIX ."brand WHERE brand_id='{$key}'";
                $brand    = $model->getRow ( $sql );
                $brand    = $brand[ 'brand_name' ] ? $brand[ 'brand_name' ] : $brand[ 'en_name' ];
                $brands[] = array ( 'brand_id' => $key, 'brand_name' => $brand,'selectID'=>0 );
            }*/;
            ksort ( $brands );
            $cateIds           = $this->getCategory ( $model, $res[ 'cateIds' ] );
            $res[ 'brandIds' ] = $brands;
            $res[ 'cateIds' ]  = $cateIds;
            //遍历出商品的id
            foreach ( $res['goods'] as $temp ){
                $ids[] = $temp['goods_id'];
            }
            $sql ="SELECT default_image FROM ".DB_PREFIX."goods WHERE goods_id in ( ".implode (',', $ids)." ) ORDER BY field(goods_id,".implode (',', $ids).")";
            $datas =$model->getAll($sql);
            //将商品和图片关联起来
            foreach($datas as $key => $value){
                $res['goods'][$key]['default_image'] =$this->common->isMySelfImage($value['default_image'], DISCOVERY_GOODS_IMG);
            }
            //计算收藏数和是否关注此商品
            $sql = "SELECT item_id  FROM ".DB_PREFIX."collect where user_id={$user_id} and type='goods' and  item_id in ( ".implode (',', $ids)." )";
            $datas=pluck($model->getAll($sql),'item_id','item_id');
            foreach($res['goods'] as $key=>$value){
                $res['goods'][$key]['collects']=$value['jcollects']+$value['collects'];
                $res['goods'][$key]['follow'] = (integer)($datas [ $res['goods'][$key]['goods_id'] ]>0);
            }
            $data['goods'] = $res['goods'];
            $data['pages'] = $res['pages'];
            $data['totalNum'] = $res['totalNum'];
            $data['cateIds'] = $res['cateIds'];
            $data['brandIds'] = $res['brandIds'];
            $this->ajax_return(FLAG_OK, '', $data);
        }
        else
        {
            $data['goods'] = '没有商品';
            $this->ajax_return ( FLAG_ERROR, '',$data );
        }


    }
    /**
     * 搜索指定数据
     *
     * @param $word
     * @param $cate_id
     * @param $brand_id
     * @param $min
     * @param $max
     * @param $sort_id
     * @param $store_id
     * @param $page
     *
     * @return array
     * @Author     lz
     * @Date&time  2016/1/6
     */
    public function searching ( $word, $cate_id, $brand_id, $min,$max, $sort_id, $store_id, $page )
    {
        $keyArr = $sort = $range = array ();
        //搜索关键词
        if ( $word )
        {
            $keyArr[] = $word;
        }
        //拼装分类条件
        if ( $cate_id )
        {
            $keyArr[] = $cate_id;
        }
        //拼装分类条件
        if ( $brand_id )
        {
            $keyArr[] = $brand_id;
        }
        //店铺ID条件
        if ( $store_id )
        {
            $keyArr[] = $store_id;
        }

        $keyword = implode ( " AND ", $keyArr );

        //拼装价格区间条件
        if ( $min > 0 && $max > 8 )
        {
            $range      = array ( "field" => "price", "from" => $min, "to" => $max );
        }

        //拼装排序条件
        if ( $sort_id == 2 )
        {
            $sort = array ( "price" => false );
        }
        elseif ( $sort_id == 3 )
        {
            $sort = array ( "price" => true );
        }
        elseif ( $sort_id == 4 )
        {
            $sort = array ( "sales" => false );
        }
        elseif ( $sort_id == 5 )
        {
            $sort = array ( "jcollects" => false );
        }
        elseif ( $sort_id == 1 )
        {
            $sort = array ( "review_time" => true );
        }
        //根据分页去请求指定的数据
        //$page = $page>1?$page:1;
        $client   = $this->rpcConnect ( 3 );
        $facet    = array ( "cate_id_two", "brand_id" );
        $result   = $client->search ( $keyword, $page, $this->size, $sort, $range, $facet );
        $totalNum = $result[ 'count' ];
        $pages    = ceil ( $totalNum / $this->size );
        if ( $pages > 100 )
        {
            $pages    = 100;
            $totalNum = $pages * $this->size;
        }

        return array (
            "goods"    => $result[ 'data' ],
            "pages"    => $pages,
            'totalNum' => $totalNum,
            "cateIds"  => $result[ 'cate_id_two' ],
            "brandIds" => $result[ 'brand_id' ]
        );
    }

    /**
     * RPC连接
     *
     * @param int $retry
     *
     * @return bool|Yar_Client
     * @Author     lz
     * @Date&time  2016/2/2
     */
    public function rpcConnect ( $retry = 3 )
    {
        try
        {
            $client = new Yar_Client( RPC_SERVER );
            $client->SetOpt ( YAR_OPT_CONNECT_TIMEOUT, 10000 );

            return $client;

        }
        catch ( Exception $e )
        {
            if ( $retry > 0 )
            {
                $this->rpcConnect ( -- $retry );
            }
            else
            {
                $this->ajax_return ( FLAG_ERROR, '网络有连接问题！' );
            }
        }
    }

    /**
     * 查询分类
     *
     * @param $model
     *
     * @return mixed
     * @author jyx
     * @date   2015/12/01
     */
    private function getCategory ( $model, $cateIds )
    {

        $cate = array();
        foreach ( $cateIds as $key => $val )
        {
            $cate[] = "$key";
        }
        /*$sql      = "SELECT cate_id,cate_name,english_name FROM " . DB_PREFIX . "gcategory WHERE store_id=0
                AND parent_id=0 AND if_show=1 ORDER BY sort_order DESC";*/
        $sql      = "SELECT cate_id,cate_name,english_name,parent_id FROM " . DB_PREFIX . "gcategory WHERE store_id=0
                AND if_show=1  ORDER BY sort_order DESC";
        $category = $model->getAll ( $sql );
        foreach($category as $cates){
            $cates[ 'name' ] = $cates[ 'cate_name' ] . '/' . trim ( mb_strtoupper ( $cates[ 'english_name' ], 'utf8' ), ' ' );
            if($cates['parent_id']==0){
                if ($list[$cates['cate_id']]) {
                    $list[$cates['cate_id']] = $list[$cates['cate_id']] + $cates;
                    unset($list[$cates['cate_id']]['parent_id']);
                }
                else{
                    $list[$cates['cate_id']] = $cates;
                    unset($list[$cates['cate_id']]['parent_id']);
                }
            }else{
                $cates['selectID']=0;
                if(in_array ( $cates[ 'cate_id' ], $cate ) ){
                    $list [ $cates ['parent_id'] ]['sub'][] = $cates;
                }
            }
        }
        $list = array_values($list);
        foreach ($list as &$temp) {
            if ($temp ['sub']) {
                $temp ['sub'] = array_values($temp ['sub']);
            }
        }
        //dd($list);
        /*if ( $category ){
            foreach ( $category as $key => $val )
            {
                $val[ 'name' ] = $val[ 'cate_name' ] . '/' . trim ( mb_strtoupper ( $val[ 'english_name' ], 'utf8' ), ' ' );
                $sql           = "SELECT cate_id,cate_name,english_name FROM " . DB_PREFIX . "gcategory WHERE store_id=0
                        AND parent_id={$val['cate_id']} AND if_show=1 ORDER BY sort_order DESC";
                $sub           = $model->getAll ( $sql );
                $subs          = array();
                if ( $sub )
                {
                    foreach ( $sub as $k => $v )
                    {
                        if ( in_array ( $v[ 'cate_id' ], $cate ) )
                        {
                            $v[ 'name' ] = $v[ 'cate_name' ] . '/' . trim ( mb_strtoupper ( $v[ 'english_name' ], 'utf8' ), ' ' );
                            $v['selectID']=0;
                            $subs[]      = $v;
                        }
                    }
                }
                $val[ 'sub' ]     = $subs;
                $category[ $key ] = $val;
            }
        }*/
        //去除没有任何商品的一级分类
        $categorys = array();
        foreach ( $list as $val )
        {
            if ( $val[ 'sub' ] )
            {
                $categorys[] = $val;
            }
        }
        return $categorys;
    }
    /**
     * 最新入住的店铺列表
     * @author jyx
     * @date 2015/08/06
     */
    public function openStore() {
        $action = '最新入住的店铺列表';
        setLogParameter($action);       //设置日志的参数
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }
        $page = $this->get_gp('page', 'G');
        $size = $this->get_gp('size', 'G');
        //检测用户是否登陆
        $user_id = $this->checkLogin();
        $size   = ($size > 0) ? intval($size) : 5;
        $page   = ($page > 0) ? intval($page) : 1;
        $offset = ($page > 0) ? ($page - 1) * $size : 0;

        $domain = get_domain().'/';
        $model = m('store');
        $sql = "SELECT s.store_id,s.store_name,s.store_logo FROM ".DB_PREFIX."store s WHERE s.state=1 AND source=".HERXI."
                ORDER BY s.add_time DESC LIMIT {$offset},{$size}";
        $data = $model->getAll($sql);
        $list = array();
        if ($data) {
            foreach ($data as $key=>$val) {
                $val['follow'] = $user_id ? $this->common->getRelationShip($user_id, $val['store_id'], 'store') : 0;//获取关注关系
                $val['store_logo'] = $val['store_logo'] ? QINIU_URL.$val['store_logo'].STORE_LOGO : $domain.Conf::get('default_goods_image');
                $sql = "SELECT g.goods_id,g.goods_name,g.price,g.introduction,g.default_image,g.is_act,gs.collects,gs.base_collects
                        FROM ".DB_PREFIX."goods g LEFT JOIN ".DB_PREFIX."goods_statistics gs ON g.goods_id=gs.goods_id
                        WHERE store_id={$val['store_id']} AND if_examine = 1 AND if_finance = 1 AND if_show = 1 AND closed = 0
                        ORDER BY add_time DESC LIMIT 0,5";
                $goods = $model->getAll($sql);
                if ($goods) {
                    foreach ($goods as $k=>$v) {
                        //查询出库存数
                        $v['total_stock'] = $this->common->getStock($v['goods_id']);
                        $v['default_image'] = $v['default_image'] ? QINIU_URL.$v['default_image'].GOODS_S_IMG : $domain.Conf::get('default_goods_image');
                        $v['introduction'] = stripslashes($v['introduction']);
                        $v['goods_name'] = stripslashes($v['goods_name']);
                        $v['collects'] = intval($v['collects'] + $v['base_collects']);
                        $v['discount'] = ($v['is_act'] == 1) ? 1 : 0;//是否优惠的商品
                        $goods[$k]=$v;
                    }
                    $val['goods'] = $goods;
                    $list[] = $val;
                }
            }
        }
        $this->ajax_return(FLAG_OK,'', $list);

    }




}